//
//  MessageListController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/1.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh

class MessageListController: UIViewController {
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.backgroundColor = UIColor.clear
            _tableView.separatorStyle = .none
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            _tableView.estimatedRowHeight = 44
            _tableView.rowHeight = UITableViewAutomaticDimension
            
            regClass(_tableView, cell: MessageListCell.self)
            //            regClass(_tableView, cell: TheTableCell.self)
            
            return _tableView
        }
    }
    
    var currentPage = 0
    var messageModels: [NotificationModel]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.title = "消息"
        
        //        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "点击", style: .done, target: self, action: #selector(doRightAction))
        
        if let handler = (UIApplication.shared.delegate as! AppDelegate).remoteNotificationHandler {
            handler(false)
        }
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        let header = MJRefreshNormalHeader {[unowned self] in
            self.getData()
        }
        header?.stateLabel.isHidden = true
        self.tableView.mj_header = header
        
        let footer = MJRefreshAutoFooter {[unowned self] in
            self.getNextPage()
        }
        self.tableView.mj_footer = footer
        
        self.tableView.mj_header.beginRefreshing()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    func doRightAction() {
        
    }
    
    func getData() {
        self.currentPage = 0
        
        if self.tableView.mj_footer.isRefreshing{
            self.tableView.mj_footer.endRefreshing()
        }
        
        NotificationModel.getMessageLists(self.currentPage) { (response) in
            if response.success {
                self.messageModels = response.value
                
                self.tableView.fin_reloadData()
            }
            else {
                WWError(response.message)
            }
            
            self.tableView.mj_header.endRefreshing()
        }
    }
    
    func getNextPage() {
        guard let modelArr = self.messageModels, modelArr.count > 0 else { //如果存储数据的数组是空的，那么久没必要下拉了，因为下拉也没数据
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
            return
        }
        guard modelArr.count >= 25 else {//因为第一页的极限是25条，如果第一次获取没有25条，说明第二页也没数据
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
            return
        }
        self.currentPage += 1
        
        NotificationModel.getMessageLists(self.currentPage) { (response) in
            if response.success {
                self.messageModels! += response.value!
                
                self.tableView.fin_reloadData()
                self.tableView.mj_footer.endRefreshing()
            }
            else {
                self.currentPage -= 1
                WWError(response.message)
            }
        }
    }
    
    //点击cell会获取DemandBaseMigrantWorkerID，然后根据这个获取对应的项目
    fileprivate func getProjectModel(_ demandBaseMigrantWorkerID: String, completion: @escaping (ProjectModel?) -> Void) {
        WWBeginLoadingWithStatus("获取消息对应的项目")
        //        ProjectModel.projectList(pageIndex: 1,keyword:demandBaseMigrantWorkerID, completionHandler: { (response) in
        //            if response.success {
        //                if let valueArr = response.value,valueArr.count > 0 {
        //                    WWEndLoading()
        //                    let model = valueArr[0]
        //                    completion(model)
        //                }
        //                else {
        //                    WWError("获取对应数据为空")
        //                    completion(nil)
        //                }
        //            }
        //            else {
        //                WWError(response.message)
        //                completion(nil)
        //            }
        //        })
        //
        ProjectModel.getProject(demandBaseMigrantWorkerID) { (response) in
            if response.success {
                if let value = response.value {
                    WWEndLoading()
                    completion(value)
                }
                else {
                    WWError("获取对应数据为空")
                    completion(nil)
                }
                
            }
            else {
                WWError(response.message)
                completion(nil)
            }
        }
    }
    
    //根据orderID获取对应的orderConfigId
    fileprivate func getOrderConfigId(_ orderId: String, completion:@escaping (String?) -> Void) {
        CommonModel.getOrderConfigId(orderId) { (response) in
            if response.success {
                completion(response.value)
            }
            else {
                WWError(response.message)
            }
        }
    }
    
}

extension MessageListController:UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messageModels?.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = getCell(tableView, cell: MessageListCell.self, indexPath: indexPath)
        //        let cell = getCell(tableView, cell: TheTableCell.self, indexPath: indexPath)
        cell.bind(self.messageModels![indexPath.row])
        return cell
    }
    
    /*点击消息后要走的流程：
     
     方式1：
     1.获取消息列表时可以取到每一个条消息的procNoticeId。现在点击cell会使用对应procNoticeId去获取对应的JsonParams。
     2.成功获取到JsonParams：
     {
     Result =     {
     Params =         {
     DemandBaseMigrantWorkerID = "afbbcaec-b34e-4d06-a2de-58d196f83329";
     };
     Type = "\U6c11\U5de5\U5de5\U8d44-\U5de5\U8d44\U53d1\U653e";
     };
     Status = OK;
     }
     *****************数据有下面情况可能：
     1.status==OK。这种情况表示获取数据成功，type一定有值
     2.status==ERROR。这种情况有两种可能，第一种是出错了；第二种是Result字段的值是空的（我们通过model不为nil，但是model.type为nil来判断），这时候就要使用『方式2』判断这个数据的信息了。
     
     方式2：
     1.判断消息的configId是否存在，不存在就不理
     2.根据configId获取对应orderConfigId。然后将获取的orderConfigId和固定的id字符串去匹配。
     3.如果没有对应的匹配就跳到详情界面
     */
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        var notificationTypeModel: NotificationTypeModel?
        
        let dispatchGroup = DispatchGroup()
        
        let messageModel = self.messageModels![indexPath.row]
        if let aId = messageModel.procNoticeId {
            
            dispatchGroup.enter()
            WWBeginLoadingWithStatus("获取消息内容")
            NotificationTypeModel.getMessageJsonParams(aId, completionHandler: { (response) in
                if response.success {
                    WWEndLoading()
                    notificationTypeModel = response.value
                }
                else {
                    WWError(response.message)
                }
                dispatchGroup.leave()
            })
        }
        
        dispatchGroup.notify(queue: DispatchQueue.main) {
            guard let model = notificationTypeModel else {
                return
            }
            if let type = model.type {
                switch type {
                case .insureInfoController: //保险信息
                    let vc = InsureInfoController()
                    self.navigationController?.pushViewController(vc, animated: true)
                case .recordPathAbnormalController://轨迹异常
                    guard let paramDict = model.params , let demandBaseMigrantWorkerID = paramDict["DemandBaseMigrantWorkerID"] as? String else {
                        return
                    }
                    
                    self.getProjectModel(demandBaseMigrantWorkerID, completion: { (model) in
                        if model != nil {
                            
                            if let signedDateString = paramDict["SignedDate"] as? String {
                                let formatter = DateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd"
                                let date = formatter.date(from: signedDateString)
                                
                                
                                let vc = RecordPathAbnormalController()
                                vc.projectModel = model
                                vc.title = "轨迹异常"
                                vc.currentDate = date
                                self.navigationController?.pushViewController(vc, animated: true)
                            }
                        }
                    })
                    
                    
                    
                case .recordSupplyFormController: //补签申请
                    guard let paramDict = model.params , let demandBaseMigrantWorkerID = paramDict["DemandBaseMigrantWorkerID"] as? String else {
                        return
                    }
                    guard let dateString = paramDict["SignedDate"] as? String else {
                        return
                    }
                    guard let date = stringToDate(dateString: dateString) else {
                        WWError("时间数据出错")
                        return
                    }
                    
                    self.getProjectModel(demandBaseMigrantWorkerID, completion: { (model) in
                        if model != nil {
                            let vc = RecordSupplyFormController()
                            vc.title = "补工申请"
                            vc.projectModel = model
                            vc.selectDate = date
                        self.navigationController?.pushViewController(vc, animated: true)
                        }
                    })
                case .salaryHomeController: //工资发放
                     break
                case .withdrawController://工资提现
                    break
                }
                
            }
            else {//这种情况：model不为nil但是type为nil，表示要通过方式2获取消息对应的内容
                
                guard let configId = messageModel.orderId else {
                    WWError("消息有误")
                    return
                }
                
//                self.getOrderConfigId(configId, completion: { (orderConfigId) in
//
//                    WWEndLoading()
                
//                    if orderConfigId != nil {
//                        if orderConfigId == "57ED0987-1C79-4C67-B6F8-23EC6304BA38" {//跳到认证
//                            let vc = CertificationReviewController()
//                            self.navigationController?.pushViewController(vc, animated: true)
//                        }
//                        else {//跳到详情界面
                        let vc = MessageDetailController()
                        vc.descriptionString = messageModel.messageDescription
                    self.navigationController?.pushViewController(vc, animated: true)
                       // }
                  //  }
                    
                    
               // })
            }
        }
    }
}
